// 量表管理 JavaScript
let currentPage = 1;
let currentFilters = {};

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查管理员token
    const adminToken = localStorage.getItem('adminToken');
    if (!adminToken) {
        showAlert('请先登录管理员账户', 'error');
        setTimeout(() => {
            window.location.href = '/admin-portal';
        }, 2000);
        return;
    }
    
    loadStatistics();
    loadScales();
    loadCategories();
});

// 加载统计信息
function loadStatistics() {
    fetch('/api/admin/scales/statistics', {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const stats = data.data;
            document.getElementById('totalScales').textContent = stats.total_scales;
            document.getElementById('publishedScales').textContent = stats.published_scales;
            document.getElementById('totalAssessments').textContent = stats.total_assessments;
            document.getElementById('memberScales').textContent = stats.member_scales;
            
            // 计算百分比
            const publishedRate = stats.total_scales > 0 ? Math.round((stats.published_scales / stats.total_scales) * 100) : 0;
            const memberRate = stats.total_scales > 0 ? Math.round((stats.member_scales / stats.total_scales) * 100) : 0;
            
            document.getElementById('publishedRate').textContent = publishedRate + '%';
            document.getElementById('memberRate').textContent = memberRate + '%';
            document.getElementById('scaleGrowth').textContent = '+' + (stats.growth || 0) + '%';
            document.getElementById('dailyAssessments').textContent = '日均 ' + (stats.daily_assessments || 0);
        }
    })
    .catch(error => console.error('Error:', error));
}

// 加载量表列表
function loadScales(page = 1) {
    currentPage = page;
    
    // 构建查询参数
    const params = new URLSearchParams({
        page: page,
        per_page: 20,
        ...currentFilters
    });
    
    fetch(`/api/admin/scales?${params}`, {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            displayScales(data.data.scales);
            displayPagination(data.data.pagination);
            updateScaleCount(data.data.pagination.total);
        } else {
            showAlert('加载量表列表失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('加载量表列表失败', 'error');
    });
}

// 显示量表列表
function displayScales(scales) {
    const tbody = document.getElementById('scalesTableBody');
    
    if (scales.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="8" class="text-center py-5">
                    <i class="bi bi-inbox fs-1 text-muted"></i>
                    <p class="mt-2 text-muted">暂无量表数据</p>
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = scales.map(scale => `
        <tr>
            <td>
                <input type="checkbox" class="form-check-input scale-checkbox" value="${scale.id}">
            </td>
            <td>
                <div>
                    <h6 class="mb-1">${scale.title}</h6>
                    <small class="text-muted">${scale.subtitle || ''}</small>
                    <div class="mt-1">
                        <small class="text-muted">${scale.question_count} 题 | 版本 ${scale.version}</small>
                    </div>
                </div>
            </td>
            <td>
                <span class="badge ${scale.is_system ? 'bg-success' : 'bg-info'}">
                    ${scale.publisher.name}
                </span>
            </td>
            <td>
                <span class="badge ${getStatusBadgeClass(scale.status)}">
                    ${getStatusText(scale.status)}
                </span>
            </td>
            <td>
                <span class="badge ${getLevelBadgeClass(scale.min_member_level)}">
                    ${getLevelText(scale.min_member_level)}
                </span>
            </td>
            <td>
                <strong>${scale.usage_count}</strong>
            </td>
            <td>
                <small>${formatDate(scale.created_at)}</small>
            </td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="viewDetail(${scale.id})" title="查看详情">
                        <i class="bi bi-eye"></i>
                    </button>
                    <button class="btn btn-outline-warning" onclick="editScale(${scale.id})" title="编辑">
                        <i class="bi bi-pencil"></i>
                    </button>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
                            <i class="bi bi-three-dots"></i>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#" onclick="setMemberLevel(${scale.id}, '${scale.title}', '${scale.min_member_level}')">
                                <i class="bi bi-star me-2"></i>设置级别
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="setStatus(${scale.id}, '${scale.title}', '${scale.status}')">
                                <i class="bi bi-gear me-2"></i>更新状态
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="#" onclick="deleteScale(${scale.id}, '${scale.title}')">
                                <i class="bi bi-trash me-2"></i>删除量表
                            </a></li>
                        </ul>
                    </div>
                </div>
            </td>
        </tr>
    `).join('');
}

// 显示分页
function displayPagination(pagination) {
    const paginationElement = document.getElementById('pagination');
    
    if (pagination.pages <= 1) {
        paginationElement.innerHTML = '';
        return;
    }
    
    let paginationHTML = '';
    
    // 上一页
    if (pagination.has_prev) {
        paginationHTML += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="loadScales(${pagination.page - 1})">上一页</a>
            </li>
        `;
    }
    
    // 页码
    for (let i = Math.max(1, pagination.page - 2); i <= Math.min(pagination.pages, pagination.page + 2); i++) {
        paginationHTML += `
            <li class="page-item ${i === pagination.page ? 'active' : ''}">
                <a class="page-link" href="#" onclick="loadScales(${i})">${i}</a>
            </li>
        `;
    }
    
    // 下一页
    if (pagination.has_next) {
        paginationHTML += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="loadScales(${pagination.page + 1})">下一页</a>
            </li>
        `;
    }
    
    paginationElement.innerHTML = paginationHTML;
}

// 更新量表数量显示
function updateScaleCount(total) {
    document.getElementById('scaleCount').textContent = `共 ${total} 个量表`;
}

// 搜索量表
function searchScales() {
    currentFilters = {
        search: document.getElementById('searchInput').value.trim(),
        status: document.getElementById('statusFilter').value,
        publisher_type: document.getElementById('publisherTypeFilter').value,
        min_member_level: document.getElementById('memberLevelFilter').value
    };
    
    // 移除空值
    Object.keys(currentFilters).forEach(key => {
        if (!currentFilters[key]) {
            delete currentFilters[key];
        }
    });
    
    loadScales(1);
}

// 设置会员级别
function setMemberLevel(scaleId, title, currentLevel) {
    document.getElementById('scaleIdForLevel').value = scaleId;
    document.getElementById('scaleTitleDisplay').value = title;
    document.getElementById('minMemberLevel').value = currentLevel;
    
    new bootstrap.Modal(document.getElementById('memberLevelModal')).show();
}

// 更新会员级别
function updateMemberLevel() {
    const scaleId = document.getElementById('scaleIdForLevel').value;
    const minMemberLevel = document.getElementById('minMemberLevel').value;
    
    fetch(`/api/admin/scales/${scaleId}/member-level`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        },
        body: JSON.stringify({
            min_member_level: minMemberLevel
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('会员级别要求更新成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('memberLevelModal')).hide();
            loadScales(currentPage);
        } else {
            showAlert('更新失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('更新失败', 'error');
    });
}

// 设置状态
function setStatus(scaleId, title, currentStatus) {
    document.getElementById('scaleIdForStatus').value = scaleId;
    document.getElementById('scaleTitleForStatus').value = title;
    document.getElementById('newStatus').value = currentStatus;
    
    new bootstrap.Modal(document.getElementById('statusModal')).show();
}

// 更新状态
function updateStatus() {
    const scaleId = document.getElementById('scaleIdForStatus').value;
    const status = document.getElementById('newStatus').value;
    
    fetch(`/api/admin/scales/${scaleId}/status`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        },
        body: JSON.stringify({
            status: status
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('状态更新成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('statusModal')).hide();
            loadScales(currentPage);
            loadStatistics();
        } else {
            showAlert('更新失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('更新失败', 'error');
    });
}

// 查看详情
function viewDetail(scaleId) {
    // 跳转到详情页面
    window.open(`/admin/scales/${scaleId}`, '_blank');
}

// 编辑量表
function editScale(scaleId) {
    // 跳转到编辑页面
    window.location.href = `/admin/scales/${scaleId}/edit`;
}

// 删除量表
function deleteScale(scaleId, title) {
    if (confirm(`确定要删除量表"${title}"吗？此操作不可撤销！`)) {
        fetch(`/api/admin/scales/${scaleId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('删除成功', 'success');
                loadScales(currentPage);
                loadStatistics();
            } else {
                showAlert('删除失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('删除失败', 'error');
        });
    }
}

// 创建量表
function createScale() {
    // 跳转到创建页面
    window.location.href = '/admin/scales/create';
}

// 刷新统计
function refreshStatistics() {
    loadStatistics();
    showAlert('统计信息已刷新', 'success');
}

// 加载分类列表
function loadCategories() {
    // 预留功能，用于加载量表分类
}

// 工具函数
function getStatusBadgeClass(status) {
    const classes = {
        'PUBLISHED': 'bg-success',
        'DRAFT': 'bg-secondary',
        'ARCHIVED': 'bg-warning'
    };
    return classes[status] || 'bg-secondary';
}

function getStatusText(status) {
    const texts = {
        'PUBLISHED': '已发布',
        'DRAFT': '草稿',
        'ARCHIVED': '已归档'
    };
    return texts[status] || status;
}

function getLevelBadgeClass(level) {
    const classes = {
        'basic': 'bg-info',
        'professional': 'bg-primary',
        'institution': 'bg-warning text-dark',
        'research': 'bg-danger'
    };
    return classes[level] || 'bg-secondary';
}

function getLevelText(level) {
    const texts = {
        'basic': '基础',
        'professional': '专业',
        'institution': '机构',
        'research': '科研'
    };
    return texts[level] || level;
}

function formatDate(dateString) {
    return new Date(dateString).toLocaleString('zh-CN');
}

function showAlert(message, type = 'info') {
    const alertClass = type === 'error' ? 'alert-danger' : 
                      type === 'success' ? 'alert-success' : 
                      type === 'warning' ? 'alert-warning' : 'alert-info';
    
    const alertHTML = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    // 在页面顶部显示提示
    const container = document.querySelector('.content-scroll');
    if (container) {
        container.insertAdjacentHTML('afterbegin', alertHTML);
        
        // 3秒后自动消失
        setTimeout(() => {
            const alert = container.querySelector('.alert');
            if (alert) {
                bootstrap.Alert.getOrCreateInstance(alert).close();
            }
        }, 3000);
    }
}

// 全选功能
document.addEventListener('DOMContentLoaded', function() {
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.scale-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    }
});

// 搜索框回车事件
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchScales();
            }
        });
    }
});